package com.huiminpay.transaction.message;

import com.alibaba.fastjson.JSONObject;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import com.huiminpay.transaction.api.service.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@RocketMQMessageListener(topic = "TP_PAYMENT_RESULT", consumerGroup = "CID_ORDER_CONSUMER")
public class TransationPayConsumer implements RocketMQListener<MessageExt> {
    @Reference
    TransactionService transactionService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] bys = messageExt.getBody();
        //String s = bys.toString();
        String body = new String(bys);
        log.info("[交易服务-消费结果消息]:{}", body);
        //转为对象
        PaymentResponseDTO responseDTO = JSONObject.parseObject(body, PaymentResponseDTO.class);
        //获得商户订单号
        String tradeNo = responseDTO.getOutTradeNo();
        //支付渠道交易流水号
        String payChanneltradeNo = responseDTO.getTradeNo();
        //交易状态
        TradeStatus tradeState = responseDTO.getTradeState();
        switch (tradeState){
            case SUCCESS:
                transactionService.updatePayOrder(tradeNo,payChanneltradeNo,"2");
                break;
            case REVOKED:
                transactionService.updatePayOrder(tradeNo,payChanneltradeNo,"4");
                break;
            case FAILED:
                transactionService.updatePayOrder(tradeNo,payChanneltradeNo,"5");
                break;
            default:
                throw new RuntimeException(String.format("无法解析交易结果:%S",tradeState));
        }

    }
}
